<!--
 * @Author: Liz.Zheng
 * @Date: 2021-11-15 16:16:07
 * @LastEditTime: 2023-02-16 19:49:28
 * @LastEditors: 郑亚莉 zhengyali@shequ.life
 * @Description: 楼宇列表
 * @Motto: Write the code. Change the world.
-->
<template>
  <div class="building-list">
    <a-card>
      <a-row type="flex" justify="space-around">
        <a-col :span="$store.getters.isMobile ? 12 : 4">
          <Statistic :value="statisticData.buildCount" suffix="栋">
            <template #title>
              <span>{{ $L("楼宇") }}数量</span>
            </template>
          </Statistic>
        </a-col>
        <a-col :span="$store.getters.isMobile ? 12 : 4">
          <Statistic :value="statisticData.management_area" suffix="㎡">
            <template #title>
              <span style="margin-right: 5px">管理面积</span>
              <Tooltip>
                <template #title>
                  <span>系统当前录入的所有{{ $L("房源") }}建筑面积总和</span>
                </template>
                <QuestionCircleOutlined />
              </Tooltip>
            </template>
          </Statistic>
        </a-col>
        <a-col :span="$store.getters.isMobile ? 12 : 4">
          <Statistic
            title="在租面积"
            :value="statisticData.rent_in_area"
            suffix="㎡"
          />
        </a-col>
        <a-col :span="$store.getters.isMobile ? 12 : 4">
          <Statistic :value="statisticData.rent_in_contract" suffix="份">
            <template #title>
              <span style="margin-right: 5px">在租合同数</span>
              <Tooltip>
                <template #title>
                  <span>如果一个合同关联了多个房间，此处会重复累加</span>
                </template>
                <QuestionCircleOutlined />
              </Tooltip>
            </template>
          </Statistic>
        </a-col>
        <a-col :span="$store.getters.isMobile ? 12 : 4">
          <Statistic
            title="待租面积"
            :value="statisticData.to_rent_area"
            suffix="㎡"
          />
        </a-col>
        <a-col :span="$store.getters.isMobile ? 12 : 4">
          <Statistic
            title="本年总营收目标"
            :value="statisticData.revenue_target_year"
            suffix="万元"
          />
        </a-col>
      </a-row>
    </a-card>
    <a-table
      :dataSource="buildingList"
      :columns="columns"
      :loading="loading"
      :pagination="pagination"
      @change="handleTableChange"
      rowKey="id"
      :scroll="{ x: 'max-content', y: $store.getters.isMobile ? 500 : 800 }"
      class="mt-10"
      sticky
    >
      <template #title>
        <a-row type="flex" class="table-header">
          <a-col flex="auto"> </a-col>
          <a-col flex="200px" class="text-right">
            <a-button
              type="primary"
              @click="buildingEdit()"
              v-permission="['buildList', 'curd', 'add']"
            >
              <template #icon>
                <PlusOutlined />
              </template>
              添加{{ $L("楼宇") }}
            </a-button>
            <a-dropdown
              :trigger="['click']"
              v-model:visible="colVisible"
              @visibleChange="handleColVisibleChange"
            >
              <InsertRowAboveOutlined
                style="font-size: 18px; cursor: pointer; margin: 0 35px"
                title="自定义列显示"
              />
              <template #overlay>
                <a-menu>
                  <a-menu-item key="reset" @click="resetColumns">
                    <a-button type="link">{{ $t("恢复默认") }}</a-button>
                  </a-menu-item>
                  <a-menu-item key="checkall">
                    <a-checkbox
                      v-model:checked="colCheckAll"
                      @change="onCheckAllChange"
                    >
                      全部
                    </a-checkbox>
                  </a-menu-item>
                  <a-menu-item v-for="item of columnsData" :key="item.key">
                    <a-checkbox
                      v-model:checked="item.checked"
                      :disabled="item.disabled"
                      @change="onCheckItemChange"
                    >
                      {{ item.title }}
                    </a-checkbox>
                  </a-menu-item>
                </a-menu>
              </template>
            </a-dropdown>
          </a-col>
        </a-row>
      </template>
      <template #bodyCell="{ text, record, index, column }">
        <template v-if="column.key === 'build_name'">
          <span>{{ record.build_name }}</span>
        </template>
        <template v-if="column.key === 'village_name'">
          <span>{{ record.village_name }}</span>
        </template>
        <template v-if="column.key === 'address'">
          <span>{{ record.address }}</span>
        </template>
        <template v-if="column.key === 'property_right'">
          <span>{{
            record.property_right == "owner"
              ? "自持"
              : record.property_right == "tenant"
              ? "承租"
              : "自持 + 承租"
          }}</span>
        </template>
        <template v-if="column.key === 'tag_arr'">
          <TagList :list="record.tag_arr" :type="2" />
        </template>
        <template v-if="column.key === 'floor_height'">
          <span>{{ record.floor_height }}</span>
        </template>
        <template v-if="column.key === 'build_area'">
          <span>{{ record.build_area }}</span>
        </template>
        <template v-if="column.key === 'property_area'">
          <span>{{ record.property_area }}</span>
        </template>
        <template v-if="column.key === 'rentable_area'">
          <span>{{ record.rentable_area }}</span>
        </template>
        <template v-if="column.key === 'self_use_area'">
          <span>{{ record.self_use_area }}</span>
        </template>
        <template v-if="column.key === 'supporting_area'">
          <span>{{ record.supporting_area }}</span>
        </template>
        <template v-if="column.key === 'parking_area'">
          <span>{{ record.parking_area }}</span>
        </template>
        <template v-if="column.key === 'management_area'">
          <span>{{ record.management_area }}</span>
        </template>
        <template v-if="column.key === 'management_areas'">
          <span>管理面积(m²)&nbsp;&nbsp;</span>
          <Tooltip>
            <template #title>
              <span>系统当前录入的所有{{ $L("房源") }}建筑面积总和</span>
            </template>
            <QuestionCircleOutlined />
          </Tooltip>
        </template>
        <template v-if="column.key === 'room_count'">
          <span>{{ record.room_count }}</span>
        </template>
        <template v-if="column.key === 'revenue_target_year'">
          <span>{{ record.revenue_target_year }}</span>
        </template>
        <template v-if="column.key === 'rent_in_precent'">
          <span>{{ record.rent_in_precent }}</span>
        </template>
        <template v-if="column.key === 'rent_in_area'">
          <span>{{ record.rent_in_area }}</span>
        </template>
        <template v-if="column.key === 'rent_in_contract'">
          <span>{{ record.rent_in_contract }}</span>
        </template>
        <template v-if="column.key === 'to_rent_area'">
          <span>{{ record.to_rent_area }}</span>
        </template>
        <template v-if="column.key === 'to_rent_room'">
          <span>{{ record.to_rent_room }}</span>
        </template>
        <template v-if="column.key === 'action'">
          <a-button
            type="link"
            @click="buildingEdit(text, record.village_id)"
            v-permission="['buildList', 'curd', 'edit']"
            >编辑</a-button
          >
          <a-button type="link" @click="layerManage(record)">楼层管理</a-button>
          <a-button
            type="link"
            danger
            @click="deleteClick(record)"
            v-permission="['buildList', 'curd', 'delete']"
            >删除</a-button
          >
        </template>
      </template>
    </a-table>
    <building-edit
      :visible="buildingEditVisible"
      :id="currentBuildingId"
      :villageId="currentBuildingVillageId"
      @cancel="handleBuildingClose"
      @success="handleBuildingSuccess"
    ></building-edit>

    <LayerManage
      :visible="layerVisible"
      :buildId="currentBuildId"
      :villageId="currentVillageId"
      @cancel="layerVisible = false"
    />
  </div>
</template>

<script>
import { defineComponent, ref, computed, watch, createVNode } from "vue";
import { PlusOutlined, QuestionCircleOutlined } from "@ant-design/icons-vue";
import request from "../../../common/utils/request";
import {
  InsertRowAboveOutlined,
  ExclamationCircleOutlined,
} from "@ant-design/icons-vue";
import { Statistic, Tooltip, Modal, message } from "ant-design-vue";
import BuildingEdit from "./modules/BuildingEdit.vue";
import LayerManage from "./modules/LayerManage.vue";
import TagList from "../../../components/Tag/show.vue";
import store from "../../../store";
import { useRouter } from "vue-router";
import BLCOMMON from "bl-common-vue3";
import dict from "../../../common/utils/dict";

const COL_RESET_TYPE = "autoBuildListColumn";
export default defineComponent({
  name: "buildList",
  components: {
    PlusOutlined,
    Statistic,
    BuildingEdit,
    TagList,
    Tooltip,
    QuestionCircleOutlined,
    InsertRowAboveOutlined,
    LayerManage,
  },
  setup() {
    const columns = ref([]);
    // 分页
    const page = ref(1);
    const limit = ref(20);
    const total = ref(0);
    const pagination = computed(() => ({
      total: total.value,
      current: page.value,
      pageSize: limit.value,
      showSizeChanger: true,
    }));
    const loading = ref(false);
    const handleTableChange = (pager, filters, sorter) => {
      page.value = pager.current;
      limit.value = pager.pageSize;
    };
    watch([page, limit], () => {
      getBuildingList();
    });

    // 请求楼宇列表
    const statisticData = ref({});
    const buildingList = ref([]);
    const getBuildingList = () => {
      request
        .get("/village", "/project/build", {
          page: page.value,
          pageSize: limit.value,
          // keywords:buildingName.value,
        })
        .then((res) => {
          statisticData.value = res.countData;
          buildingList.value = res.list;
          total.value = res.total;
        });
    };

    // 编辑楼宇
    const buildingEditVisible = ref(false);
    const currentBuildingId = ref(0);
    const currentBuildingVillageId = ref(0);
    const buildingEdit = (id, villageId) => {
      currentBuildingId.value = id ? id : 0;
      currentBuildingVillageId.value = villageId ? villageId : 0;
      buildingEditVisible.value = true;
    };
    const handleBuildingClose = () => {
      buildingEditVisible.value = false;
    };
    const handleBuildingSuccess = () => {
      handleBuildingClose();
      getBuildingList();
    };

    // 楼层管理
    const layerVisible = ref(false);
    const currentBuildId = ref(0);
    const currentVillageId = ref(0);
    const layerManage = (record) => {
      currentBuildId.value = record.id;
      currentVillageId.value = record.village_id;
      layerVisible.value = true;
    };

    // 删除楼宇
    const deleteClick = ({ id, village_id }) => {
      Modal.confirm({
        title: () => `确认删除该${BLCOMMON.utils.L("楼宇")}吗?`,
        icon: () => createVNode(ExclamationCircleOutlined),
        centered: true,
        onOk() {
          request
            .del("/village", "/project/build", { id, village_id })
            .then((res) => {
              message.success(res.msg || "删除成功");
              getBuildingList();
              store.dispatch("GetUserInfo");
            });
        },
      });
    };

    // 搜索楼宇
    const buildingName = ref("");
    const onBuildingSearch = () => {
      page.value = 1;
      getBuildingList();
    };
    const fixedCol = ["build_name"];
    const widthCol = ["address"];
    const customCols = [
      "build_name",
      "village_name",
      "build_number",
      "address",
      "property_right",
      "tag_arr",
      "floor_height",
      "build_area",
      "property_area",
      "rentable_area",
      "self_use_area",
      "supporting_area",
      "parking_area",
      "management_area",
      "room_count",
      "revenue_target_year",
      "rent_in_precent",
      "rent_in_area",
      "rent_in_contract",
      "to_rent_area",
      "to_rent_room",
      "action",
    ];

    // 列表筛选
    const colCheckAll = ref(false);
    const colVisible = ref(false);
    const handleColVisibleChange = (visiable) => {
      if (visiable == false) {
        // 调取接口存住选项
        getColumns();
        request
          .post("org", "/user/specialSetting", {
            type: dict.BUILD_LIST_COL_SET,
            content: JSON.stringify(columnsData.value),
          })
          .then(() => {});
      }
    };
    const onCheckAllChange = (e) => {
      const { checked } = e.target;
      colCheckAll.value = checked;
      columnsData.value.forEach((item) => {
        if (!item.disabled) {
          item.checked = checked;
        }
      });
    };
    const getColumns = () => {
      let arr = [];
      let checkall = true;
      columnsData.value.forEach((item) => {
        if (item.key == "build_name") {
          item.title = BLCOMMON.utils.L("楼宇名称");
        }
        if (item.key == "village_name") {
          item.title = BLCOMMON.utils.L("所属项目");
        }
        if (item.key == "tag_arr") {
          item.title = BLCOMMON.utils.L("楼宇标签");
        }
        if (item.checked) {
          let col = {
            title: item.title,
            dataIndex: item.key,
            width: 150,
          };
          if (customCols.includes(item.key)) {
            col.key = item.key;
          }
          if (fixedCol.includes(item.key)) {
            col.fixed = store.getters.isMobile ? undefined : "left";
          }
          if (widthCol.includes(item.key)) {
            col.width = store.getters.isMobile ? 700 : 150;
          }

          arr.push(col);
        } else if (checkall) {
          checkall = false;
        }
      });
      colCheckAll.value = checkall;
      columns.value = [
        ...arr,
        {
          title: "操作",
          dataIndex: "id",
          key: "action",
          fixed: "right",
          width: 240,
        },
      ];
    };
    const columnsData = ref([]);
    const columnsList = (type, init = false) => {
      let params = {};
      if (type) {
        params.type = type;
        params.list_type = dict.BUILD_LIST_COL_SET;
      } else {
        params.type = dict.BUILD_LIST_COL_SET;
      }
      request.get("/org", "/org/buildListColumn", params).then((res) => {
        columnsData.value = res.list;
        getColumns();
        if (init) {
          getBuildingList();
        }
      });
    };
    const resetColumns = () => {
      columnsList(COL_RESET_TYPE);
      colVisible.value = false;
    };
    const onCheckItemChange = (e) => {
      const { checked } = e.target;
      if (checked && columnsDataCheckAll()) {
        colCheckAll.value = true;
      } else {
        colCheckAll.value = false;
      }
    };
    // 是否全选
    const columnsDataCheckAll = () => {
      for (let i in columnsData.value) {
        if (!columnsData.value[i].checked) {
          return false;
        }
      }
      return true;
    };

    const init = () => {
      columnsList(null, true);
    };
    init();

    return {
      resetColumns,
      loading,
      columns,
      buildingList,
      pagination,
      statisticData,
      buildingEditVisible,
      currentBuildingId,
      currentBuildingVillageId,
      buildingName,
      columnsData,
      colCheckAll,
      colVisible,
      handleTableChange,
      buildingEdit,
      onBuildingSearch,
      handleBuildingClose,
      handleBuildingSuccess,
      handleColVisibleChange,
      onCheckItemChange,
      onCheckAllChange,
      layerManage,
      deleteClick,
      layerVisible,
      currentBuildId,
      currentVillageId,
    };
  },
});
// const columns = [
//   { title: "楼宇名称", dataIndex: "build_name", fixed: "left", width: 150 },
//   { title: "所属项目", dataIndex: "village_name", width: 150 },
//   { title: "楼宇编号", dataIndex: "build_number", width: 150 },
//   {
//     title: "楼宇标签",
//     width: 150,
//     dataIndex: "tags",
//     key: "tags",
//   },
//   { title: "楼宇地址", dataIndex: "address", width: 150 },
//   {
//     title: "产权性质",
//     dataIndex: "property_right",
//     key: "property_right",
//     width: 150,
//   },
//   { title: "产权面积（㎡）", dataIndex: "property_area", width: 150 },
//   { title: "建筑面积（㎡）", dataIndex: "build_area", width: 150 },
//   { title: "管理面积（㎡）", dataIndex: "management_area", width: 150 },
//   { title: "房间总数（间）", dataIndex: "room_count", width: 150 },
//   {
//     title: "本年营收目标（万元）",
//     dataIndex: "revenue_target_year",
//     width: 150,
//   },
//   { title: "出租率（%）", dataIndex: "rent_in_precent", width: 150 },
//   { title: "在租面积（㎡）", dataIndex: "rent_in_area", width: 150 },
//   { title: "在租合同数（份）", dataIndex: "rent_in_contract", width: 150 },
//   { title: "待租面积（㎡）", dataIndex: "to_rent_area", width: 150 },
//   { title: "待租房间数（间）", dataIndex: "to_rent_room", width: 150 },
//   {
//     title: "操作",
//     dataIndex: "id",
//     key: "action",
//     fixed: "right",
//     width: 100,
//   },
// ];
</script>

<style lang="less" scoped>
.building-list {
  padding: 10px;
  .table-header {
    padding: 0 10px;
    font-weight: bold;
  }
}
:deep(.ant-btn-link) {
  margin-right: 0;
}
</style>
